//
//  UserViewController.m
//  BYX
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "UserViewController.h"
#import "UserCell.h"
#import "CollectListViewController.h"
#import "AlarmClockViewController.h"
#import "HelpViewController.h"
#import "SaveTools.h"
#import "DKNightVersion.h"
#import "UIImageView+NightImage.h"
@interface UserViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIImageView *picView;
@end

@implementation UserViewController

-(void)dealloc
{
    [_tableView release];
    [_picView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.nightBackgroundColor = UIColorFromRGB(0x343434);
    [self createNavigation];
    [self createImage];
    [self createHeaderPic];
    [self createTableView];
}

#pragma  mark -
#pragma mark 创建导航栏
- (void)createNavigation
{
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:86/255.0 green:137/255.0 blue:156/255.0 alpha:1];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 60, 0, 60, 33)];
    titleLabel.text = @"我的药箱";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont fontWithName:@"Baskerville-SemiBold" size:20];
    self.navigationItem.titleView = titleLabel;
    [titleLabel release];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.nightBarTintColor = UIColorFromRGB(0x444444);
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:86/255.0 green:137/255.0 blue:156/255.0 alpha:1];
    
}

#pragma mark -
#pragma mark 创建tableView
- (void)createImage
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"2.png" ofType:nil]];
    [self.view addSubview:imageView];
    [imageView release];
}
#pragma mark -
#pragma mark 创建头像

- (void)createHeaderPic
{
    self.picView = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 100) / 2, 20, 100, 100)];

    [self.view addSubview:self.picView];
    self.picView.layer.cornerRadius =  self.picView.frame.size.width / 2;
    self.picView.layer.masksToBounds = YES;
    self.picView.userInteractionEnabled = YES;
    NSString *path = [SaveTools pathWithName:@"image" directory:NSDocumentDirectory];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    if (image == nil) {
        self.picView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Tou.png" ofType:nil]];
        self.picView.nightImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Tou.png" ofType:nil]];
    }else
    {
        self.picView.image = image;
        self.picView.nightImage = image;
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(picAction:)];
    [self.picView addGestureRecognizer:tap];
    [tap release];
    [_picView release];
    
}

//头像点击事件

- (void)picAction:(id)sender
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.allowsEditing = YES;
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self presentViewController:picker animated:YES completion:nil];
    [picker release];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info;
{
    NSString *path = [SaveTools pathWithName:@"image" directory:NSDocumentDirectory];
    [UIImagePNGRepresentation([info objectForKey:@"UIImagePickerControllerEditedImage"]) writeToFile:path atomically:YES];
    
    self.picView.image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    self.picView.nightImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -
#pragma mark 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 130, self.view.frame.size.width, self.view.frame.size.height - 230) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    
    self.tableView.nightBackgroundColor = UIColorFromRGB(0x343434);
    self.tableView.nightSeparatorColor = UIColorFromRGB(0x313131);
    [_tableView release];
    
}
#pragma mark -
#pragma mark 分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
//每个分区行数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
        case 1:
            return 2;
            break;
        case 2:
            return 3;
            break;
        default:
            return 0;
    }
}

//自定义cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify= @"cellIdentify";
    UserCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell) {
        cell = [[UserCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentify];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator;
    switch (indexPath.section) {
        case 0:
            [cell valueWithIndex:indexPath.row];
            break;
        case 1:
            [cell valueWithIndex:indexPath.row + 2];
            break;
        default:
            [cell valueWithIndex:indexPath.row + 4];
            break;
    }
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
            NSString *path = [paths lastObject];
            
            NSString *str = [NSString stringWithFormat:@"%.1fM", [self folderSizeAtPath:path]];
            cell.detailTextLabel.textColor = [UIColor blackColor];
            cell.detailTextLabel.text = str;
            
        }
    }if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    }
    return cell;
}

//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            CollectListViewController *collect = [[CollectListViewController alloc] init];
            [collect getTab:self.tabBarController navC:self.navigationController];
            [self.navigationController pushViewController:collect animated:YES];
            
            [collect release];
        }else
        {
            AlarmClockViewController *alarm = [[AlarmClockViewController alloc] init];
            [self presentViewController:alarm animated:YES completion:nil];
            [alarm release];
        }
    }else if (indexPath.section == 2)
    {
        HelpViewController *help = [[HelpViewController alloc] init];
        help.tag = indexPath.row;
        [self presentViewController:help animated:YES completion:nil];
        [help release];
    }
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
            NSString *path = [paths lastObject];
            
            NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
            for (NSString *p in files) {
                NSError *error;
                NSString *Path = [path stringByAppendingPathComponent:p];
                if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
                    [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
                }
            }
            [self.tableView reloadData];
            
        }
    }
}


#pragma mark -
#pragma mark 清理缓存
- (long long) fileSizeAtPath:(NSString*) filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
@end
